package com.places.googleplacesandmaps;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


@TargetApi(9)
public class MainActivity extends Activity {

	// flag for Internet connection status
	Boolean isInternetPresent = false;

	// Connection detector class
	ConnectionDetector cd;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	// Google Places
	GooglePlaces googlePlaces;

	// Places List
	PlacesList nearPlaces;
	
	// Place Details
		PlaceDetails placeDetails;

	// GPS Location
	GPSTracker gps;

	// Button
	Button btnShowOnMap;

	// Progress dialog
	ProgressDialog pDialog;
	
	// Places Listview
	ListView lv;
	
	// Type of places to search
	String types; 
		
	// Name of places to search
	String names; 
	
	// ListItems data
	ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
	ArrayList<String> places_found = new ArrayList<String>();
	ArrayList<String> open_time = new ArrayList<String>();
	ArrayList<String> close_time = new ArrayList<String>();
	
	// KEY Strings
	public static String KEY_REFERENCE = "reference"; // id of the place
	public static String KEY_NAME = "name"; // name of the place
	public static String KEY_VICINITY = "vicinity"; // Place area name
	
	
	JSONArray jArray;
	JSONObject json_data;
	String userchoice = "";
	String topen_str = "empty",tclose_str = "empty";
	String tuser_str = "";
	EditText txtUsername;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//txtUsername = (EditText)findViewById(R.id.txtUsername);
		Intent intent = getIntent();
		types = intent.getStringExtra("types");
		names = intent.getStringExtra("names");
		tuser_str  = intent.getStringExtra("time");
		userchoice = intent.getStringExtra("day");
		
		
		
	//	*********************************fetch data from server
		InputStream is=null;
    	String line = null;
    	String result="";
    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectNetwork() // or .detectAll() for all detectable problems
        .penaltyDialog()  //show a dialog
        .permitNetwork() //permit Network access 
        .build());
	  try{
        	
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new      
            HttpPost("http://project2.site11.com/getTime.php");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.i("postData", response.getStatusLine().toString());
        }catch(Exception e)
        {
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
        
        
        //parsing http response into string
        System.out.println("6");
        long h=1;
        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            System.out.println("before converting");
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection" +e.toString());
        }
        
        
        //parsing json
        try
        {	 if(result!=null)
        {	
        	
            
            
            jArray = new JSONArray(result);
            System.out.println("7,1");
           
        }
            }catch(JSONException e){
            Log.e("log_tag", "Error parsing data" +e.toString());
        }
        
	//	********************************

   //********************************push data to server
        
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    	
    	nameValuePairs.add(new BasicNameValuePair("StoreID","30"));
        /*nameValuePairs.add(new BasicNameValuePair("name",item.getName()));
        nameValuePairs.add(new BasicNameValuePair("note",item.getNote()));
        nameValuePairs.add(new BasicNameValuePair("time",String.valueOf(item.getDueTime())));
        nameValuePairs.add(new BasicNameValuePair("notimeflag",String.valueOf(item.isNoDueTime())));
        nameValuePairs.add(new BasicNameValuePair("priority",String.valueOf(item.getPriority())));
        nameValuePairs.add(new BasicNameValuePair("checked",String.valueOf(item.isChecked())));
        nameValuePairs.add(new BasicNameValuePair("synced","1"));
        */
   /* 	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectNetwork() // or .detectAll() for all detectable problems
        .penaltyDialog()  //show a dialog
        .permitNetwork() //permit Network access 
        .build()); 
      //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://project2.site11.com/addTime.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            //HttpEntity entity = response.getEntity();
            //InputStream is = entity.getContent();
            Log.i("postData", response.getStatusLine().toString());
            txtItemName.setText("30");
           
        }

        catch(Exception e)
        {
            Log.e("log_tag", "Error in http connection "+e.toString());
            
        }
       */ 
    	
   //*********************************     
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		isInternetPresent = cd.isConnectingToInternet();
		if (!isInternetPresent) {
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}

		// creating GPS Class object
		gps = new GPSTracker(this);

		// check if GPS location can get
		if (gps.canGetLocation()) {
			Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
		} else {
			// Can't get user's current location
			alert.showAlertDialog(MainActivity.this, "GPS Status",
					"Couldn't get location information. Please enable GPS",
					false);
			// stop executing code by return
			return;
		}

		// Getting listview
		lv = (ListView) findViewById(R.id.list);
		
		// button show on map
		btnShowOnMap = (Button) findViewById(R.id.btn_show_map);

		// calling background Async task to load Google Places
		// After getting places from Google all the data is shown in listview
		new LoadPlaces().execute();

		/** Button click event for shown on map */
		btnShowOnMap.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				Intent i = new Intent(getApplicationContext(),
						PlacesMapActivity.class);
				// Sending user current geo location
				i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
				i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
				
				// passing near places to map activity
				i.putExtra("near_places", nearPlaces);
				i.putExtra("places_found",places_found);
				// staring activity
				startActivity(i);
			}
		});
		
		
		/**
		 * ListItem click event
		 * On selecting a listitem SinglePlaceActivity is launched
		 * */
		lv.setOnItemClickListener(new OnItemClickListener() {
 
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	// getting values from selected ListItem
                String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
                googlePlaces = new GooglePlaces();
                open_time.clear();
                close_time.clear();
    			// Check if used is connected to Internet
    			try {
    				placeDetails = googlePlaces.getPlaceDetails(reference);

    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    			String address = placeDetails.result.vicinity;
    			String days[]={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    			try
				{
					for(int i=0;i<jArray.length();i++)
					{
						json_data = jArray.getJSONObject(i);
						String loc = json_data.getString("Location");
						if(loc.equals(address))
						{
							String type = json_data.getString("Type");
							if(type.equals("open"))
							{
								for(int j=0;j<=6;j++)
									open_time.add(json_data.getString(days[j]));
							}
								
							else
							{
								for(int j=0;j<=6;j++)
									close_time.add(json_data.getString(days[j]));
							}
								
						}
					}
				}
				catch(JSONException e){
		            Log.e("log_tag", "Error parsing data" +e.toString());
				}
    			//txtUsername.setText(open_time.get(4));
    			
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        SinglePlaceActivity.class);
                
                // Sending place refrence id to single place activity
                // place refrence id used to get "Place full details"
                in.putExtra(KEY_REFERENCE, reference);
                in.putExtra("user_latitude", Double.toString(gps.getLatitude()));
				in.putExtra("user_longitude", Double.toString(gps.getLongitude()));
				in.putExtra("open_time", open_time);
				in.putExtra("close_time", close_time);
                startActivity(in);
            }
        });
	}

	/**
	 * Background Async Task to Load Google places
	 * */
	class LoadPlaces extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			// creating Places class object
			googlePlaces = new GooglePlaces();
			
			try {
				// Separeate your place types by PIPE symbol "|"
				// If you want all types places make it as null
				// Check list of types supported by google
				// 
				//String types = "cafe|restaurant"; // Listing places only cafes, restaurants
				//String types = null;
				// Radius in meters - increase this value if you don't find any places
				double radius = 1000; // 1000 meters 
				
				// get nearest places
				nearPlaces = googlePlaces.search(gps.getLatitude(),
						gps.getLongitude(), radius, types, names);
				
				

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * and show the data in UI
		 * Always use runOnUiThread(new Runnable()) to update UI from background
		 * thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed Places into LISTVIEW
					 * */
					// Get json response status
					String status = nearPlaces.status;
					
					// Check for all possible status
					if(status.equals("OK")){
						// Successfully got places details
						if (nearPlaces.results != null) {
							// loop through each place
							for (Place p : nearPlaces.results) {
								
								HashMap<String, String> map = new HashMap<String, String>();
								try
								{
									for(int i=0;i<jArray.length();i++)
									{
										json_data = jArray.getJSONObject(i);
										String loc = json_data.getString("Location");
										if(loc.equals(p.vicinity))
										{
											
											String type = json_data.getString("Type");
											if(type.equals("open"))
												topen_str = json_data.getString(userchoice);
											else
												tclose_str = json_data.getString(userchoice);
										}
									}
								}
								catch(JSONException e){
						            Log.e("log_tag", "Error parsing data" +e.toString());
								}
								
								if(!topen_str.equals("empty"))
								{
									DateFormat formatter = new SimpleDateFormat("HH:mm");
									try{
										Date topen_dt = (Date) formatter.parse(topen_str);
										Date tclose_dt = (Date) formatter.parse(tclose_str);
										Date tuser_dt = (Date) formatter.parse(tuser_str);
										//txtUsername.setText(tuser_str);
										//txtUsername.setText(tuser_dt.toString());
										long topen = topen_dt.getTime();
										long tclose = tclose_dt.getTime();
										long tuser = tuser_dt.getTime();
										if(tuser>=topen && tuser<tclose)
										{
											map.put(KEY_REFERENCE, p.reference);
											
											// Place name
											map.put(KEY_NAME, p.name);
											places_found.add(p.vicinity);
											
											//map.put(KEY_VICINITY,p.vicinity);
											
											
											// adding HashMap to ArrayList
											placesListItems.add(map);
										}
										
										
									}
									catch (ParseException e) {
										// TODO Auto-generated catch block
											e.printStackTrace();
										} 
										
									topen_str = "empty";
									tclose_str = "empty";
								}
								
							}
							// list adapter
							ListAdapter adapter = new SimpleAdapter(MainActivity.this, placesListItems,
					                R.layout.list_item,
					                new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
					                        R.id.reference, R.id.name });
							
							// Adding data into listview
							lv.setAdapter(adapter);
						}
					}
					else if(status.equals("ZERO_RESULTS")){
						// Zero results found
						alert.showAlertDialog(MainActivity.this, "Near Places",
								"Sorry no places found. Try to change the types of places",
								false);
					}
					else if(status.equals("UNKNOWN_ERROR"))
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry unknown error occured.",
								false);
					}
					else if(status.equals("OVER_QUERY_LIMIT"))
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry query limit to google places is reached",
								false);
					}
					else if(status.equals("REQUEST_DENIED"))
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry error occured. Request is denied",
								false);
					}
					else if(status.equals("INVALID_REQUEST"))
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry error occured. Invalid Request",
								false);
					}
					else
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry error occured.",
								false);
					}
				}
			});

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	

}
